package serv

import (
	"crypto/md5"
	"erp/model"
	"erp/service"
	"erp/utils"
	"fmt"
	"net/http"
	"reflect"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func AdminUserCtrl(c *gin.Context) {
	if c.Request.Method == "POST" {
		param := GetJsonData(c)

		var adminUserArr []model.AdminUser
		page := int(param["page"].(float64))
		limit := int(param["limit"].(float64))

		where := "1"

		if param["name"] != nil {
			where += " and name like '%%" + param["name"].(string) + "%%'"
		}
		if param["username"] != nil {
			where += " and username like '%%" + param["username"].(string) + "%%'"
		}

		dbEngine.Table("f_admin_user").Cols("id,role_id,role_name, username,name, balance, org_name,phone,create_time,status").Where(where).Limit(limit, (page-1)*limit).Find(&adminUserArr)
		cnt, _ := dbEngine.Table("f_admin_user").Where(where).Count()
		if adminUserArr == nil {
			adminUserArr = []model.AdminUser{}
		}

		c.JSON(200, ApiList{
			Status: 200,
			Data: ApiDataListObj{
				Total:       cnt,
				PerPage:     0,
				CurrentPage: 0,
				LastPage:    0,
				Data:        adminUserArr,
			},
		})
	} else {
		c.HTML(http.StatusOK, "admin-user-list.html", nil)
	}
}

func AdminUserGetUpdateInfoCtrl(c *gin.Context) {
	param := GetJsonData(c)
	id := param["id"]

	nodeArr := map[string]any{}
	dbEngine.Table("f_admin_user").Select("id,name,username,role_id,org_name,balance,note,create_time,status,phone").Where("id=?", id).Get(&nodeArr)

	c.JSON(200, map[string]any{"status": 200, "data": nodeArr})
}

func AdminUserUpdateCtrl(c *gin.Context) {
	param := GetJsonData(c)
	var err error
	var msg string

	if param["phone"] == nil || param["phone"].(string) == "" {
		c.JSON(200, map[string]any{"status": 500, "msg": "手机号不能为空！"})
		return
	}

	if param["id"] == nil {
		user := service.GetUserByUsername(param["username"].(string))
		if user.Id > 0 {
			c.JSON(200, map[string]any{"status": 500, "msg": "用户名不能重复"})
			return
		}

		user = service.GetUserByPhone(param["phone"].(string))
		if user.Id > 0 {
			c.JSON(200, map[string]any{"status": 500, "msg": "手机号不能重复"})
			return
		}
		param["create_time"] = time.Now().Format("2006-01-02 15:04:05")
		_, err = dbEngine.Table("f_admin_user").Insert(param)
		msg = "添加成功"
	} else {
		user := service.GetUserByUsername(param["username"].(string))
		if user.Id > 0 && user.Id != int(param["id"].(float64)) {
			c.JSON(200, map[string]any{"status": 500, "msg": "用户名不能重复"})
			return
		}

		user = service.GetUserByPhone(param["phone"].(string))
		if user.Id > 0 && user.Id != int(param["id"].(float64)) {
			c.JSON(200, map[string]any{"status": 500, "msg": "手机号不能重复"})
			return
		}

		_, err = dbEngine.Table("f_admin_user").Where("id=?", param["id"]).Update(param)
		msg = "更新成功"
	}

	if err != nil {
		c.JSON(200, map[string]any{"status": 500, "msg": "填写的信息不正确！" + err.Error()})
	} else {
		c.JSON(200, map[string]any{"status": 200, "msg": msg})
	}
}

func AdminUserDeleteCtrl(c *gin.Context) {
	param := GetJsonData(c)
	id, _ := param["id"].(float64)
	fmt.Print(reflect.TypeOf(param["id"]))

	if id < 2 {
		c.JSON(200, map[string]any{"status": 500, "msg": "没有权限"})
		c.Abort()
		return
	}

	dbEngine.Table("f_admin_user").Where("id=?", id).Delete()
	c.JSON(200, map[string]any{"status": 200, "msg": "删除成功"})
}

func AdminUserResetPwdCtrl(c *gin.Context) {
	param := GetJsonData(c)
	id, _ := strconv.Atoi(utils.Strval(param["id"]))
	if id == 0 {
		id = c.GetInt("userId")
		// c.JSON(200, map[string]any{"status": 500, "msg": "参数错误"})
		// c.Abort()
		// return
	}

	dbEngine.Table("f_admin_user").Where("id=?", id).Update(map[string]any{
		"password": fmt.Sprintf("%x", md5.Sum([]byte(utils.Strval(param["pwd"])))),
	})

	c.JSON(200, map[string]any{"status": 200, "msg": "密码修改成功"})
}
